/**
 * Created by lx on 17/6/8.
 */

define(['text!style/home.css', 'text!module/home/home.html'], function(css,tpl) {

    var home = function() {
        var search = {
            init: function() {
                this.request();
            },
            request: function() {
                var self = this;
                $.ajax({
                    url: './data/data.json',
                    type: 'post',
                    dataType: 'json',
                    success: function (data) {
                        if (data.returnCode !== '0000') return;
                        appView.html(tpl);
                        document.getElementsByTagName("style")[0].innerHTML = css;

                        var TClass = data.returnData.TClass,//一级条件
                            TechClass = data.returnData.TechClass,//二级条件
                            TGradeClass = data.returnData.TGradeClass,//三级条件
                            provinceObj = data.returnData.province; //所有全国省份
                        self.until = {
                            // 多级菜单数据格式
                            // self.CLASS.catIds = {
                            //     { "level_1": "2|22|222"},
                            //     {"level_2": "2|22|222"},
                            //     { "level_3": "2|22|222"}
                            //     .........
                            //     };
                            "catIds": {},
                            //获取点击菜单的li对象
                            "menuTextObj": null,
                        };
                        //渲染菜单第一个条件的ul
                        var select_1 = TClass.map(function (val) {
                            return '<li data-tid="' + val.TID + '">' + val.TName + '</li>';
                        });
                        $("#info-ZZ").html(select_1.join(''));

                        //渲染省份列表
                        var compiled = _.template($("#province-tpl").html());
                        $("#top_city").html(compiled({provinceObj: provinceObj}));

                        //事件
                        self.bindEvent(TechClass, TGradeClass);
                    }
                });
            },
            bindEvent: function(TechClass, TGradeClass) {
                var self = this;
                //点击空白处隐藏菜单信息栏
                $('.title, .wrap').off().on('touchstart', function(e) {
                    var attrClass = $(e.target).attr('class') || $(e.target).parent('.title').attr('class'),
                        menuInfoObj = $("#menu-info");
                    if ((attrClass === 'title' || attrClass === 'wrap') && menuInfoObj.css('display') === 'block') {
                        menuInfoObj.hide();
                    }
                });
                //头部事件代理
                $(".condition").off().on('touchstart', function(e) {
                    var targetObj = $(e.target),
                        menuHeight = $("#menu").children('nav:first-child').height() - 0;//获取第一个nav的高度
                    parentNodeId = (targetObj.parents('#menu').attr('id') || targetObj.parents('#menu-info').attr('id')) || targetObj.attr('id');
                    //菜单选择事件
                    if (parentNodeId === 'menu') {
                        self.menuEvent(targetObj, menuHeight);
                    }
                    //菜单信息选择事件
                    if (parentNodeId === 'menu-info') {
                        self.menuInfoEvent(targetObj, TechClass, TGradeClass);
                    }
                    //增加菜单事件
                    if (parentNodeId === 'add-condition') {
                        self.addMenuEvent(menuHeight);
                    }
                    //删除菜单事件
                    if (parentNodeId === 'del-condition') {
                        self.delMenuEvent();
                    }
                    //搜索事件
                    if (parentNodeId === 'search-condition') {
                        self.searchEvent();
                    }
                });

                //内容事件代理
                $("#result-msg").off().on('touchstart', function(e) {
                    var targetObj = $(e.target),
                        targetId = (targetObj.attr('id') || targetObj.parent('#top_city').attr('id')) || targetObj.parents('#content').attr('id');
                    //点击"全国"事件
                    if (targetId === 'select-province') {
                        self.countryEvent(targetObj);
                    }

                    //点击"省份"事件
                    if (targetId === 'top_city') {
                        self.provinceEvent();
                    }

                    //点击"内容列表项"事件
                    if (targetId === 'content') {
                        var companyId = targetObj.parents('li').attr('data-id') || targetObj.attr('data-id');
                        self.listInfoEvent(companyId);
                    }
                });
            },
            menuEvent: function(targetObj, menuHeight) {
                var self = this,
                    dataType = targetObj.attr('data-type') || targetObj.parent().attr('data-type'),
                    navNode = targetObj.parents('nav'),
                    navLen = navNode.attr('nav-len') || 1,
                    navHeight = navNode.attr('nav-height') || 50,
                    infoObj = $("#info-" + dataType);
                self.until.menuTextObj = targetObj.parent('li').length != 0 ? targetObj.parent('li') : targetObj;
                var topHeight = navLen * navHeight + menuHeight;
                if (infoObj.css('display') === 'block') {
                    infoObj.hide().siblings().hide();
                } else {
                    infoObj.show().siblings().hide();
                }
                $("#menu-info").css("top", topHeight + 'px').show().attr("ul-level", "level_"+navLen);
            },
            menuInfoEvent: function(targetObj, TechClass, TGradeClass) {
                //取条件值的正则匹配,第一个(\d+)是一级条件,第二个(\d+)是二级条件,第三个(\d+)是三级条件
                var reg = /(\d+)\|(\d+)\|(\d+)/g,
                    self = this,
                    classId = (targetObj.attr('data-tid') || targetObj.attr('data-tclassid')) || targetObj.attr('data-tgclassid');
                pNodeId = targetObj.parents('ul').attr('id');
                pNodeLevel = targetObj.parents('.menu-info').attr('ul-level') || 'level_1';
                menuTextObj = self.until.menuTextObj;
                if (classId && pNodeId == 'info-ZZ') {
                    var select_2 = [];
                    TechClass.forEach(function(val) {
                        if (val.TType == classId) {
                            select_2.push('<li data-tclassid="' + val.TClassID + '">' + val.TechName + '</li>');
                        }
                    });

                    //获取的条件数据
                    if (self.until.catIds[pNodeLevel]) {
                        self.until.catIds[pNodeLevel] = self.until.catIds[pNodeLevel].replace(reg, classId + "|$2|$3");
                    } else {
                        self.until.catIds[pNodeLevel] = classId + "|00|000";
                    }

                    targetObj.parent().hide().next().html(select_2.join(''));
                    menuTextObj.find('.child-type').css('color', '#000').text(targetObj.text());
                    menuTextObj.next().find('.child-type').text('选择资质类型');

                } else if (classId && pNodeId == 'info-ZY' ) {
                    var select_3 = [];
                    var firstTGradeClass;
                    TGradeClass.forEach(function(val) {
                        if (val.TClassID == classId) {
                            select_3.push('<li data-tgclassid="' + val.TGClassID + '">' + val.TGradeName + '</li>');
                            if (!firstTGradeClass) firstTGradeClass = {"TGradeName": val.TGradeName, "TGClassID": val.TGClassID};
                        }
                    });

                    //获取的条件数据
                    self.until.catIds[pNodeLevel] = self.until.catIds[pNodeLevel].replace(reg, "$1|" + classId + "|" + firstTGradeClass['TGClassID']);

                    targetObj.parent().hide().next().html(select_3.join(''));
                    menuTextObj.find('.child-type').css('color', '#000').text(targetObj.text());
                    menuTextObj.next().find('.child-type').text(TGradeClass[0].TGradeName);

                } else if (classId && pNodeId == 'info-DJ') {
                    //获取的条件数据
                    self.until.catIds[pNodeLevel] = self.until.catIds[pNodeLevel].replace(reg, "$1|$2|" + classId);

                    targetObj.parent().hide();
                    menuTextObj.find('.child-type').css('color', '#000').text(targetObj.text());
                }
            },
            addMenuEvent: function(menuHeight) {
                var menuObj = $("#menu");
                var navHtml = '<nav> <ul class="menu-nav"> <li data-type="ZZ"> <p class="child-type">资质类型</p> <p class="demoSpan1"></p> </li> <li data-type="ZY"> <p class="child-type">专业类型</p> <p class="demoSpan1"></p> </li> <li data-type="DJ"> <p class="child-type">等级</p> <p class="demoSpan1"></p> </li> </ul> </nav>';
                menuObj.append(navHtml);
                var len = menuObj.find('nav').length;
                menuObj.children('nav:last-child').attr('nav-len', len).attr('nav-height', menuHeight + 9);
                $("#del-condition").show();
            },
            delMenuEvent: function() {
                var len = $("#menu nav").length;
                if (len === 2) {
                    $("#del-condition").hide();
                    $(".menu-info").hide();
                }
                $("#menu nav:last-child").remove();
            },
            searchEvent: function() {
                var self = this;
                $.ajax({
                    url: './data/company.json',
                    method: 'post',
                    data: {"catids": self.until.catIds},
                    dataType: 'json',
                    success: function(res) {
                        if (res.returnCode !== '0000') return;
                        var compiled = _.template($("#content-tpl").html());
                        $("#content ul").html(compiled({"company": res.returnData.list}));

                        $("#menu nav:first-child").siblings().remove();
                        $("#menu-info").hide();
                        $(".result-search").show().find('.result-count-label').text(res.returnData.count);
                        $("#content").show();
                        $("#del-condition").hide();
                    }
                });
            },
            countryEvent: function(targetObj) {
                var height = $("#top_city").height();
                var provinceHeight = $(".province").height()
                if (provinceHeight == 0) {
                    targetObj.children().addClass('demoSpan2');
                    $(".province").css("height", height);
                } else {
                    targetObj.children().removeClass('demoSpan2');
                    $(".province").css("height", 0);
                }
            },
            provinceEvent: function() {

            },
            listInfoEvent: function(id) {
                location.href = '#details/'+id;
            }
        }
        search.init();
    }
    return home;
});